import parse from "./parseAst.js";
import { checkString } from './utils.js';

function templateStr (word, globalConfig) {
  const str = word?.replace(/{{[\s\S]*?}}/ig, '');
  if(str?.trim()){
    globalConfig.userHandle?.push(word);
  }
}

function recursion(ast, globalConfig, filename) {
  const reg = /{{[\s\S]*?}}/i;
  let arr = []; //记录要收集的code
  ast?.forEach((item) => {
    if (item.outerText?.length > 0) {
      item.outerText.forEach((word) => {
        if (!word.trim?.()) return;
        if (reg.test(word)) {
          // 细分处理
          templateStr(word, globalConfig);
        } else {
          if(!checkString(word, globalConfig)) return;
          arr.push(word);
          globalConfig.saveReplaceObj[filename].textData.push(word);
        }
      });
    }
    // 解析innerText <span>asg</span> <span>aa{{asg}}bb</span>
    if (item?.innerText?.trim?.()) {
      if (reg.test(item.innerText)) {
        templateStr(item.innerText, globalConfig);
      } else {
        if(!checkString(item.innerText, globalConfig)) return;
        arr.push(item.innerText);
        globalConfig.saveReplaceObj[filename].textData.push(item.innerText);
      }
    }
    // 解析attrs ok
    if (item.attrsData?.length > 0) {
      arr.push(...item.attrsData);
    }
    if (item.children?.length > 0) {
      arr = [...arr, ...recursion(item.children, globalConfig, filename)];
    }
  });
  return arr;
}

function astToObj(data, globalConfig, filename) {
  const temp = /<template>[\s\S]*<\/template>/gi;
  let arr = [];
  let obj = null;
  globalConfig.saveReplaceObj[filename] = {
    textData: [],
    attrData: [],
    jsTextData: [],
  };
  data.replace(temp, function (word) {
    // 语法树
    obj = parse(word, globalConfig, filename);
    // 解析模板
    arr = recursion(obj, globalConfig, filename);
  });
  return {
    obj,
    arr,
  };
}

export default astToObj;